package xtreamclient

import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okhttp3.*
import org.apache.commons.lang3.RandomStringUtils
import java.io.IOException
import java.net.URLEncoder
import java.util.logging.Level.FINE
import okhttp3.OkHttpClient
import io.netty.util.ResourceLeakDetector.setLevel
import java.util.concurrent.TimeUnit
import java.util.logging.Level
import java.util.logging.Logger


class HTTPVLCHandler() : VLCHandler{
    private var currentHTTPPassword: String? = null
    var isConnected = false
    override var process: Process? = null
    var client = OkHttpClient()



    override fun connect() {
        startVLC()
        buildClientWithAuthentication()

    }

    private fun buildClientWithAuthentication() {
        client = OkHttpClient.Builder().authenticator(object : Authenticator {
            override fun authenticate(route: Route?, response: Response): Request? {
                val credString = Credentials.basic("", currentHTTPPassword ?: "")
                return response.request.newBuilder().header("Authorization", credString).build()
            }
        }).connectTimeout(2,TimeUnit.SECONDS).readTimeout(2,TimeUnit.SECONDS).build()

        Logger.getLogger(OkHttpClient::class.java.name).level = Level.FINE
    }

    fun restartVLC() {
        process?.destroyForcibly()
        connect()
    }

    fun closeVLC() {
        process?.destroyForcibly()
    }

    override fun playItem(streamURL: String, streamName: String) {
        try {
            val requestStop = Request.Builder()
                .url("http://127.0.0.1:8096/requests/status.xml?command=in_stop")
                .build()
            val res_stop = client.newCall(requestStop).execute()
            res_stop.body?.close()

            Thread.sleep(500)
            val request = Request.Builder()
                .url("http://127.0.0.1:8096/requests/status.xml?command=in_play&input=${URLEncoder.encode(streamURL,"UTF-8")}")
                .build()
            val res = client.newCall(request).execute()
            res.body?.close()
            //println(res.body?.string())
        } catch (e: IOException) {
            process?.destroy()
            process?.destroyForcibly()
            startVLC()
            /*
            val request = Request.Builder()
                .url("http://127.0.0.1:8096/requests/status.xml?command=in_play&input=${URLEncoder.encode(streamURL,"UTF-8")}")
                .build()
            val res = client.newCall(request).execute()
            res.body?.close()*/
        }

    }



    private fun startVLC() {
        process = null
        val length = 10
        val useLetters = true
        val useNumbers = false
        val generatedString = RandomStringUtils.random(length, useLetters, useNumbers)
        currentHTTPPassword = generatedString
        val rt = Runtime.getRuntime()
        val rtstring = "\"C:\\Program Files\\VideoLAN\\VLC\\vlc.exe\"  --extraintf http --http-host 127.0.0.1 --http-port 8096 --http-password $currentHTTPPassword --width=100 --height=100"
        println("Starting VLC with $rtstring")
        process = rt.exec(rtstring)

        println("HTTP-Password: $currentHTTPPassword")
        GlobalScope.launch{
            printLogs()
        }
    }

}